package base_NIO.NIO;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(6666));
        //设置为非阻塞
        ssc.configureBlocking(false);
        //定义多路复用选择器
        Selector sel = Selector.open();
        //注册accept事件
        ssc.register(sel, SelectionKey.OP_ACCEPT);
        while(true){
            //select()在没有收到相关事件时产生阻塞，直到
            //有事件触发，阻塞才会得以释放
            sel.select();
            //获取所有的请求的事件
            Set<SelectionKey> sks = sel.selectedKeys();
            Iterator<SelectionKey> iter = sks.iterator();
            while(iter.hasNext()){
                SelectionKey sk = iter.next();
                if(sk.isAcceptable()){
                    ServerSocketChannel ssc1=
                            (ServerSocketChannel)sk.channel();
                    SocketChannel sc = ssc1.accept();
                    while(sc==null){
                        sc = ssc1.accept();
                    }
                    sc.configureBlocking(false);
                    //为sc注册read和write事件
                    //0000 0001  OP_READ
                    //0000 0100  OP_WRITE
                    //0000 0101  OP_READ和OP_WRITE
                    sc.register(sel, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
                    System.out.println("提供服务的线程id:"+
                            Thread.currentThread().getId());
                }
                if(sk.isWritable()){
                }
                if(sk.isReadable()){
                }
                iter.remove();
            }
        }
    }
}
